package lv.dysnomia.songs.util

import java.lang.StringBuilder

/**
 * Wiki markup is divided into lines, each line is space-normalized. 
 * Each segment of consecutive nonempty lines becomes one text paragraph. 
 *  
 */
object WikiProcessor {
  val separators: Array[Char] = Array('\n')

  /**
   * q == 0, iff there has been an empty line before
   * q == 1, iff some list-item has started before
   * q == 2, iff some text paragraph has started before
   */
  def toHtml(wiki: String): String = {
    val lines = wiki.split(separators)
    val sb = new StringBuilder
    var q = 0
    for (line <- lines) {
      if (q == 0 && lineType(line) == 0) {
        // echo the text
        sb.append(line + "\n")
        q = 0
      } else if (q == 0 && lineType(line) == 1) {
        // start new list
        sb.append("<ol class='lyrics'><li>" + replace(line) + "\n")
        q = 1
      } else if (q == 0 && lineType(line) == 2) {
        // start new paragraph
        sb.append("<p>" + line + "\n")
        q = 2
      } else if (q == 1 && lineType(line) == 0) {
        // terminate the list
        sb.append("</li></ol>" + line + "\n")
        q = 0
      } else if (q == 1 && lineType(line) == 1) {
        // make a new item within the current list
        sb.append("</li>\n<li>" + replace(line) + "\n")
        q = 1
      } else if (q == 1 && lineType(line) == 2) {
        // append one more line to the current item in the list
        sb.append(line + "\n")
        q = 1
      } else if (q == 2 && lineType(line) == 0) {
        // terminate the current paragraph
        sb.append("</p>" + line + "\n")
        q = 0
      } else if (q == 2 && lineType(line) == 1) {
        // terminate the current paragraph and start a new list
        sb.append("</p>\n<ol class='lyrics'><li>" + replace(line) + "\n")
        q = 1
      } else if (q == 2 && lineType(line) == 2) {
        // append one more line to the current paragraph
        sb.append(line + "\n")
        q = 2
      }
    }
    if (q == 1) {
      sb.append("</li></ol>")
    } else if (q == 2) {
      sb.append("</p>")
    }
    return sb.toString
  }

  def lineType(line: String): Int = {
    if (line.trim.equals("")) 0
    else if (line.trim.startsWith("#")) 1
    else 2
  }
  
  def replace(line:String): String = {
	return line.replaceFirst("^# +","")
  }

}